package com.hefeng.unit.common;


import com.hefeng.common.redis.service.RedisService;
import com.hefeng.unit.domain.GyDeviceReport;
import com.hefeng.unit.domain.entity.UserDto;
import com.hefeng.unit.domain.entity.UserInfo;
import com.hefeng.unit.mapper.GyDeviceUserMapper;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 方法说明: 项目启动加载
 * @param
 * @return null
 * @Author: huzh
 * @Date: 2022/10/13
 */
@Service
public class StartLoadingParameter implements ApplicationRunner {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    GyDeviceUserMapper gyDeviceUserMapper;
    @Autowired
    RedisService redisService;

    public static  String getAccessTokenUrl="http://47.109.55.87:18081/gasApi/gas-auth/applogin";
    //报警存储持久化list
    public static List <GyDeviceReport> DataList=new CopyOnWriteArrayList<GyDeviceReport>();
    //redis 存储
    public  static final String BINDING="UserBindingList";
    //查询设备信息
    public static  String QUERYBYDEVICECODE="http://47.109.55.87:18081/gasApi/collection/deviceInfo/queryByDeviceCode/";
    //更新设备信息
    public static  String DEVICEUPDATEINFO="http://47.109.55.87:18081/gasApi/collection/deviceInfo/wxEditDeviceInfo";
    public static String loginData="Y2hlbmdkdSVnYXNfYXV0aF9vcml6YXRpb24lZTEwYWRjMzk0OWJhNTlhYmJlNTZlMDU3ZjIwZjg4M2U=";
    public static String  DETEVTOR="http://47.109.55.87:18081/gasApi/collection/deviceInfo/wxGetAegisDetectorInfoList/";
    public static Map<String,String> paramMap=new HashMap<String,String>();
    public static Map<String, UserDto> userDtoMap = new HashMap<String, UserDto>();
    @Override
    public void run(ApplicationArguments args) {
        try {
          //  获取用户与设备绑定关系
            setUserDindingDevice();
            getBindingUserByDeviceCode();
           // 燃气大屏登录鉴权
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 方法说明: 获取燃气采集平台token
     *
     * @param getAccessTokenUrl
     * @return null
     * @Author: huzh
     * @Date: 2022/10/13
     */
    public void getAccessToken(String getAccessTokenUrl) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("autoLogin", true);
        map.put("encrypt", "aGVmZW5nJWdhc19hdXRoX29yaXphdGlvbiVlMTBhZGMzOTQ5YmE1OWFiYmU1NmUwNTdmMjBmODgzZQ==");
        map.put("username", "hefeng");
        map.put("password", "e10adc3949ba59abbe56e057f20f883e");
        HttpEntity<?> request = new HttpEntity<>(map);
        ResponseEntity<JSONObject> res = restTemplate.postForEntity(getAccessTokenUrl, request, JSONObject.class);
        JSONObject data = res.getBody();
        try {
            paramMap.put("userId", data.getJSONObject("obj").getString("userId"));
            paramMap.put("tokenHead", data.getJSONObject("obj").getString("tokenHead"));
            paramMap.put("token", data.getJSONObject("obj").getString("token"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

//    public void getBindingUserByDeviceCode() {
//        List<Map<String, String>> list = gyDeviceUserMapper.getUserBindingDevice();
//        list.forEach(i -> {
//            UserDto userDto = new UserDto();
//            userDto.setDeviceCode(i.get("deviceCode"));
//            String[] ids = i.get("userIds").split(",");
//            userDto.setUserId(Arrays.asList(ids));
//            String[] phones = i.get("phones").split(",");
//            userDto.setPhone(Arrays.asList(phones));
//            userDtoMap.put(userDto.getDeviceCode(), userDto);
//            //redisService.setCacheObject(userDto.deviceCode, userDto);
//        });
//    }

    public void getBindingUserByDeviceCode() {
        List<Map<String, String>> list = gyDeviceUserMapper.getUserBindingDevice();
        list.forEach(i -> {
            UserDto userDto = new UserDto();
            userDto.setDeviceCode(i.get("deviceCode"));
            String[] ids = i.get("userIds").split(",");
            userDto.setUserId(Arrays.asList(ids));
            String[] phones = i.get("phones").split(",");
            userDto.setPhone(Arrays.asList(phones));
            userDtoMap.put(userDto.getDeviceCode(), userDto);
            //redisService.setCacheObject(userDto.deviceCode, userDto);
        });
    }
    public void setUserDindingDevice() {
        //清空缓存
       // redisService.deleteObject("UserBindingList");
        List<Map<String, String>> list = gyDeviceUserMapper.getUserBindingDevice();
        List<UserInfo> userInfos = new ArrayList<>();
        list.forEach(i -> {
            try {
                String[] ids = i.get("userIds").split(",");
                String[] phones = i.get("phones").split(",");
                for (int v = 0; v < ids.length; v++) {
                    UserInfo user = new UserInfo();
                    user.setDeviceCode(i.get("deviceCode"));
                    user.setUserId(ids[v]);
                    user.setPhone(phones[v]);
                    userInfos.add(user);
                }
                //数据添加到缓存里
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        //redisService.setCacheList("UserBindingList", userInfos);
    }



}
